import type { MutableRefObject } from 'react';
import { CascaderProps } from './index';
import { request, getCookie } from '@inbiz/utils';
const version = InbizConfig.API_VERSION;

const canvert = (data: any, id: string) => {
  return data?.map?.((item: any) => {
    item[id.split('$')[1]] = item[id.split('$')[1]].toString();
    if (item.child) {
      item.child = canvert(item.child, id);
    }
    return item;
  });
};

export function getData(params: {
  appId: string;
  id: string;
  sourceKey: string;
  parentId: string;
  value: string | number;
}) {
  const { appId, id, ...rest } = params;
  if (!params.id) {
    return Promise.resolve({ data: [] });
  }
  return request(`/inbiz/api/services/front/modelengine/v${version}/assembly/treeDatas/${appId}`, {
    params: {
      ...rest,
      id: id.split('$')[0],
      token: getCookie('token'),
    },
    // }).then((res) => ({ data: params.value === 0 ?res.Data : res.Data?.[0].child || [] })); // 强行包装一个只有一个元素的 Data 数组，接口问题
  }).then((res) => ({
    data:
      params.value === 0
        ? canvert(res.Data, params.id)
        : canvert(res.Data?.[0].child, params.id) || [],
  })); // 强行包装一个只有一个元素的 Data 数组，接口问题
}

export function getPathName(params: {
  appId: string;
  id: string;
  sourceKey: string;
  sourceType: number;
  parentId: string;
  name: string;
  values: (string | number)[];
}): Promise<{ [p: string]: any; path: string; namepath: string }[]> {
  const { appId, id, ...rest } = params;
  
  return request(
    `/inbiz/api/services/front/modelengine/v${version}/assembly/TreeParentIdDatas/${appId}`,
    {
      params: {
        ...rest,
        id: id.split('$')[0],
        values:params?.values?params?.values?.join(','):'',
        token: getCookie('token'),
      },
    },
  );
}

type events = MutableRefObject<CascaderProps['callBackEvents']>;
type Service<TData, TParams extends any> = (args: TParams) => Promise<TData>;

export function apiWrapper<TParams, TData, E extends events>(
  fn: Service<TData, TParams>,
  events: E,
  fieldNames: {
    onParamFormat: string;
    onData: string;
    onRequest: string;
  },
) {
  const { onParamFormat, onData, onRequest } = fieldNames;
  return function (args: Parameters<typeof fn>[number]) {
    let reqArgs = args;
    if (events.current?.[onParamFormat]) {
      reqArgs = events.current[onParamFormat](reqArgs);
    }
    const reqFn = (events.current?.[onRequest] as typeof fn) || fn;
    return reqFn(reqArgs).then((res) => {
      if (events.current?.[onData]) {
        return events.current[onData](res) as TData;
      } else {
        return res;
      }
    });
  };
}

export async function getDocumentInfo(docmentIds: string, props: any) {
  let url = '';
  if (props.childModelConfig) {
    url = `/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/business/selectDatas`;
  }
  if (docmentIds && !props.childModelConfig) {
    return Promise.resolve(docmentIds);
  } else if (props.childModelConfig) {
    // 3a0521f18fb570a10ef0b1709811d0f3

    return request
      .post(url, {
        data: {
          name: props.storageConfig.name,
          data: {
            ref_id: props.inbiz?.queryData?.id,
            controlid: props.controlId,
          },
        },
      })
      .then((res) => {
        const list: Array<any> = res?.data ?? [];
        return list;
      });
  }
  return undefined;
}
